#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mosquitto.h>

void on_connect(struct mosquitto *mosq, void *obj, int rc) {
    printf("连接回调: rc=%d\n", rc);
    if (rc == 0) {
        printf("✅ 连接成功!\n");
    } else {
        printf("❌ 连接失败: ");
        switch(rc) {
            case 1: printf("协议版本不支持\n"); break;
            case 2: printf("客户端ID不合法\n"); break;
            case 3: printf("代理服务器不可用\n"); break;
            case 4: printf("用户名或密码错误\n"); break;
            case 5: printf("未授权\n"); break;
            default: printf("未知错误 (%d)\n", rc); break;
        }
    }
}

void on_disconnect(struct mosquitto *mosq, void *obj, int rc) {
    printf("断开连接: rc=%d\n", rc);
}

int main() {
    struct mosquitto *mosq;
    int rc;
    
    printf("=== MQTT连接调试测试 ===\n");
    
    // 初始化
    mosquitto_lib_init();
    
    // 创建实例
    mosq = mosquitto_new("debug_client", true, NULL);
    if (!mosq) {
        printf("❌ 创建mosquitto实例失败\n");
        return 1;
    }
    
    // 设置回调
    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_disconnect_callback_set(mosq, on_disconnect);
    
    // 测试多个代理
    const char* brokers[] = {
        "localhost",
        "test.mosquitto.org", 
        "broker.emqx.io",
        NULL
    };
    
    for (int i = 0; brokers[i] != NULL; i++) {
        printf("\n🔌 测试连接到: %s\n", brokers[i]);
        
        rc = mosquitto_connect(mosq, brokers[i], 1883, 10);
        if (rc != MOSQ_ERR_SUCCESS) {
            printf("❌ 发起连接失败: %s\n", mosquitto_strerror(rc));
            continue;
        }
        
        // 短暂的网络循环测试连接
        for (int j = 0; j < 50; j++) {  // 5秒超时
            rc = mosquitto_loop(mosq, 100, 1);
            if (rc != MOSQ_ERR_SUCCESS) {
                printf("❌ 网络循环错误: %s\n", mosquitto_strerror(rc));
                break;
            }
            usleep(100000);  // 0.1秒
        }
        
        mosquitto_disconnect(mosq);
        sleep(1);
    }
    
    // 清理
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
    
    printf("\n测试完成\n");
    return 0;
}

/*
编译: gcc -o mqtt_debug mqtt_debug.c -lmosquitto
运行: ./mqtt_debug
*/